package cn.gxufe.reliable.message.admin.schedule.mq;

import cn.gxufe.reliable.message.admin.domain.RMessage;
import cn.gxufe.reliable.message.admin.mapper.MessageMapper;
import cn.gxufe.reliable.message.admin.mq.MqProducer;
import cn.gxufe.reliable.message.common.Message;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author yingjie.rong
 **/
@Component
public class SendMessageToMqService {

    private  static final Logger logger = LoggerFactory.getLogger(SendMessageToMqService.class);

    @Autowired
    private MessageMapper messageMapper;

    private Gson gson = new Gson();

    @Autowired
    private MqProducer mqProducer ;

    @Scheduled(fixedDelay = 1000)
    public synchronized void exec(){
        List<RMessage> messages = messageMapper.selectCanSend(new Date(System.currentTimeMillis() - (5 * 1000)));
        for (RMessage message: messages   ) {
            try {
                sendAndUpdateTime(message);
                logger.info( "id = {}, key = {} send ok !",message.getId(),message.getKey() );
            }catch (Throwable e){
                logger.error( "id = "+message.getId()+", key = "+message.getKey()+" send error !",e);
            }
        }
    }

    public void sendAndUpdateTime(RMessage message){
        Message msg = new Message();
        msg.setData(message.getData());
        msg.setStatus(message.getStatus());
        msg.setHeader(message.getHeader());
        msg.setKey(message.getKey());
        msg.setId(message.getId());
        String json = gson.toJson(msg);
        mqProducer.send(json);
        messageMapper.updateForSend(Message.STATUS_CONFIRM,message.getId());
    }

}
